package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<ShopType> queryTypeList() {
        // 1.判断再redis中是否有缓存
        List<String> keyList=new ArrayList<>();
        for (int i = 1; i < 11; i++) {
            String key = RedisConstants.SHOP_TYPE_KEY +i;
            keyList.add(key);
        }
        List<String> stringList = stringRedisTemplate.opsForValue().multiGet(keyList);
        // 2.有那么直接从redis中获取数据并返回
        if(stringList!=null && stringList.stream().noneMatch(str -> str == null || str.isEmpty())) {
            return stringList.stream()
                    .map(json -> JSONUtil.toBean(json, ShopType.class))
                    .collect(Collectors.toList());
        }
        // 3.没有则查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        // 4.将数据转换成map
        Map<String, String> map = IntStream.range(0, keyList.size())
                .boxed()
                .collect(Collectors.toMap(
                        i -> keyList.get(i),  // key
                        i -> JSONUtil.toJsonStr(typeList.get(i)) // value
                ));

        // 5.将数据存入redis中
        stringRedisTemplate.opsForValue().multiSet(map);
        // 6.返回查询结果
        return typeList;
    }
}
